#include <uart.h>
#include "rtthread.h"

void Uart_Init(void)
{
	  uint16_t u16RxData;
    en_result_t enRet = Ok;
    uint32_t u32Fcg1Periph = PWC_FCG1_PERIPH_USART1 | PWC_FCG1_PERIPH_USART2 | \
                             PWC_FCG1_PERIPH_USART3 | PWC_FCG1_PERIPH_USART4;
    const stc_usart_uart_init_t stcInitCfg = {
        UsartIntClkCkNoOutput,
        UsartClkDiv_1,
        UsartDataBits8,
        UsartDataLsbFirst,
        UsartOneStopBit,
        UsartParityNone,
        UsartSamleBit8,
        UsartStartBitFallEdge,
        UsartRtsEnable,
    };

    /* Enable peripheral clock */
    PWC_Fcg1PeriphClockCmd(u32Fcg1Periph, Enable);

    /* Initialize USART IO */
    PORT_SetFunc(USART_RX_PORT, USART_RX_PIN, USART_RX_FUNC, Disable);
    PORT_SetFunc(USART_TX_PORT, USART_TX_PIN, USART_TX_FUNC, Disable);

    /* Initialize UART */
   USART_UART_Init(USART_CH, &stcInitCfg);

    /* Set baudrate */
   USART_SetBaudrate(USART_CH, USART_BAUDRATE);

    /*Enable RX && TX function*/
    USART_FuncCmd(USART_CH, UsartRx, Enable);
    USART_FuncCmd(USART_CH, UsartTx, Enable);
}
INIT_BOARD_EXPORT(Uart_Init);

void rt_hw_console_output(const char *str)
{
		rt_size_t i = 0, size = 0;
		char a = '\r';
		size = rt_strlen(str);
		for (i = 0; i < size; i++)
			{
				if (*(str + i) == '\n')
				{
					while (Reset == USART_GetStatus(USART_CH, UsartTxEmpty))  /* Warit Tx data register empty */
          {
          }
					USART_SendData(USART_CH,(uint16_t)a);
				}
				while (Reset == USART_GetStatus(USART_CH, UsartTxEmpty))  /* Warit Tx data register empty */
        {
        }
				USART_SendData(USART_CH,(*(str + i)));
			}
}

char rt_hw_console_getchar(void)
{
		int ch = -1;
			if (Set == USART_GetStatus(USART_CH, UsartRxNoEmpty))
			{
					ch = USART_RecData(USART_CH);
			}

		return ch;
}